﻿// ===================================
// <copyright>
// This file is part of LABSMFController.
//
//    LABSMFController is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    LABSMFController is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with LABSMFController.  If not, see <http://www.gnu.org/licenses/>.
//    Copyright 2011 David Bakker
//
//</copyright>
// <author>David Bakker</author>
// <email>mailto:DavidFBakker@gmail.com</email>
// <created>Saturday, May 07, 2011</created>
// <lastedit>Saturday, May 07, 2011</lastedit>
// ===================================

using System;
using System.Ext;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace LABSMFController.LABS.Services
{
    internal class StreamingSocketsService : BeerService
    {
        private int MAXSockets;
        private Socket[] _clientSockets;
        private object _locker;
        private Thread _myClientSocketThread;
        private Thread _myServerSocketThread;

        private void SetSocket(Socket socket)
        {
            for (int c = 0; c < MAXSockets; c++)
            {
                if (_clientSockets[c] == null)
                {
                    _clientSockets[c] = socket;
                    return;
                }
            }
        }

        public override void Configure()
        {
            _locker = new object();
            MAXSockets = 4;
            Console.Write("StreamingSocketsService configure");
            _clientSockets = new Socket[MAXSockets];
        }

        public override void Start()
        {
            BeerProgram.Log("StreamingSocketsService starting");
            _myServerSocketThread = new Thread(SocketServiceThread);

            _myServerSocketThread.Start();
        }

        public override void Stop()
        {
            if (_myServerSocketThread != null)
                _myServerSocketThread.Abort();

            if (_myClientSocketThread != null)
                _myClientSocketThread.Abort();

            BeerProgram.Log("StreamingSocketsService stoping");
        }

        private void SocketServiceThread()
        {
            const Int32 cPort = 12000;

            // Create a socket, bind it to the server's port, and listen for client 
            // connections.
            var server = new Socket(AddressFamily.InterNetwork,
                                    SocketType.Stream, ProtocolType.Tcp);
            var localEndPoint = new IPEndPoint(IPAddress.Any, cPort);
            server.Bind(localEndPoint);
            server.Listen(Int32.MaxValue);

            while (true)
            {
                // Wait for a client to connect.
                Socket clientSocket = server.Accept();

                // Process the client request.  true means asynchronous.
                SetSocket(clientSocket);
                // new ProcessClientRequest(clientSocket, true);
            }
        }

        public void SendToClients(string message)
        {
            if (_clientSockets == null) return;

            for (int c = 0; c < MAXSockets; c++)
            {
                if (_clientSockets[c] == null) continue;

                string mes = message + "\r\n";
                try
                {
                    Socket s = _clientSockets[c];
                    int a = _clientSockets[c].Available;
                    _clientSockets[c].Send(Encoding.UTF8.GetBytes(mes));
                }
                catch (Exception)
                {
                    lock (_locker)
                    {
                        _clientSockets[c].Close();
                        _clientSockets[c] = null;
                    }
                }
            }
        }
    }
}